package com.yitong.base.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;

import com.alibaba.fastjson.JSONObject;

/**
 * 时间、文件、文件夹操作类
 * 
 * @author Administrator
 * 
 */
public class Tools {
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	static Logger log = Logger.getLogger(Tools.class);
	public static Properties prop;

	/**
	 * 获取系统时间(年月日)
	 * 
	 * @return String
	 */
	public static String getSystemTime() {
		String time = sdf.format(new Date());
		System.out.println(time);
		return time;
	}

	/**
	 * 获取系统时间(年月日时分秒)
	 * 
	 * @return
	 */
	public static String getNowTime() {
		String time = sdf1.format(new Date());
		return time;
	}

	public static String getTodayTimestamp() {
		Calendar cal = Calendar.getInstance();
		Date today = cal.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String date = sdf.format(today);
		return date;
	}

	/***************************************************************************
	 * 获取当前日期
	 * 
	 * @return String
	 */
	public static String getToday() {
		Calendar cal = Calendar.getInstance();
		Date today = cal.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(today);
		String year = date.substring(0, 2);
		String month = date.substring(3, 5);
		String day = date.substring(6, 8);
		date = "20" + year + "-" + month + "-" + day;
		return date;
	}

	/***************************************************************************
	 * 获取前一天的日期
	 * 
	 * @return
	 */
	public static String getYesterday() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		java.util.Date d = cal.getTime();
		SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
		String yesterday = spf.format(d);
		System.out.println(yesterday);
		return yesterday;
	}

	/**
	 * 获取当前以前n天的日期
	 * 
	 * @param day
	 * @return
	 */
	public static String getBefore(int n) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, 0 - n);
		java.util.Date d = cal.getTime();
		SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
		String yesterday = spf.format(d);
		System.out.println(yesterday);
		return yesterday;
	}

	/**
	 * 获取指定时间以前n天的日期
	 * 
	 * @param day
	 * @return
	 */
	public static String getBefore(Date date, int n) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, 0 - n);
		java.util.Date d = cal.getTime();
		SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
		String yesterday = spf.format(d);
		System.out.println(yesterday);
		return yesterday;
	}

	/**
	 * 获取当前后n天的日期
	 * 
	 * @param day
	 * @return
	 */
	public static String getAfter(int n) {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, n);
		java.util.Date d = cal.getTime();
		SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
		String yesterday = spf.format(d);
		System.out.println(yesterday);
		return yesterday;
	}

	/**
	 * 获取指定时间后n天的日期
	 * 
	 * @param day
	 * @return
	 */
	public static String getAfter(Date date, int n) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, n);
		java.util.Date d = cal.getTime();
		SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
		String yesterday = spf.format(d);
		System.out.println(yesterday);
		return yesterday;
	}

	/**
	 * 获取后一天的日期
	 * 
	 * @return
	 */
	public static String getTomorrow() {
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, 1);
		java.util.Date d = cal.getTime();
		SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
		String yesterday = spf.format(d);
		System.out.println(yesterday);
		return yesterday;
	}

	/** 获取本月1号* */
	public static String getMonthFirstday() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar
				.getActualMinimum(Calendar.DAY_OF_MONTH));
		return sdf.format(calendar.getTime());
	}

	@SuppressWarnings("unused")
	public static String getMonthLastday() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca
				.getActualMinimum(Calendar.DAY_OF_MONTH));
		return null;
	}

	/** 下个月1号 * */
	public static String getNextMonthFirstday() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DAY_OF_MONTH, calendar
				.getActualMinimum(Calendar.DAY_OF_MONTH));
		return sdf.format(calendar.getTime());

	}

	/**
	 * 获取当前日期是星期几<br>
	 * 
	 * @param dt
	 * @return 当前日期是星期几
	 */
	public static String getWeekOfDate(Date dt) {
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		System.out.println(weekDays[w]);
		return weekDays[w];
	}

	/** 本周第一天* */
	public static String getWeekFirstday() {

		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_WEEK, calendar
				.getActualMinimum(Calendar.DAY_OF_WEEK));
		return sdf.format(calendar.getTime());

	}

	// 用来全局控制 上一周，本周，下一周的周数变化
	private static int weeks = 0;

	/**
	 * 获得当前日期与本周一相差的天数
	 * 
	 * @return
	 */
	private static int getMondayPlus() {
		Calendar cd = Calendar.getInstance();
		// 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
		int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
		if (dayOfWeek == 1) {
			return -6;
		} else {
			return 2 - dayOfWeek;
		}
	}

	/**
	 * 获得星期一的日期
	 * 
	 * @return
	 */
	public static String getCurrentMonday() {
		weeks = 0;
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus);
		Date monday = currentDate.getTime();
		// DateFormat df = sdf.getDateInstance();
		String preMonday = sdf.format(monday);
		return preMonday;
	}

	/**
	 * 获得上周星期一的日期
	 * 
	 * @return
	 */
	public static String getPreviousMonday() {
		weeks--;
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
		Date monday = currentDate.getTime();
		String preMonday = sdf.format(monday);
		System.out.print(preMonday);
		return preMonday;
	}

	/**
	 * 获得星期天的日期
	 * 
	 * @return
	 */
	public static String getCurrentSunday() {
		weeks = 0;
		int mondayPlus = getMondayPlus();
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.add(GregorianCalendar.DATE, mondayPlus - 1);
		Date monday = currentDate.getTime();
		// DateFormat df = sdf.getDateInstance();
		String preMonday = sdf.format(monday);
		return preMonday;
	}

	/**
	 * 获取当年第一时间
	 * 
	 * @return
	 */
	public static String getYearFirstTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		return sdf.format(new Date()) + "-01-01 00:00:00";
	}

	/**
	 * 取得上个月今天的日期
	 * 
	 * @return
	 */
	public static String getBeforeMonth() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -1); // 得到前一个月
		System.out.println(sdf.format(calendar.getTime()));
		return sdf.format(calendar.getTime());
	}

	/** 获取上个月1号* */
	public static String getbeforeMonthFirstday() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -1);
		calendar.set(Calendar.DAY_OF_MONTH, calendar
				.getActualMinimum(Calendar.DAY_OF_MONTH));
		System.out.println(sdf.format(calendar.getTime()));
		return sdf.format(calendar.getTime());
	}

	/** 获取上月的最后一天 */
	public static String getLastDayOfLastMonth() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar ca = Calendar.getInstance();
		ca.add(Calendar.MONTH, -1);
		ca.set(Calendar.DAY_OF_MONTH, 1);
		df.format(ca.getTime());
		ca.add(Calendar.MONTH, 1);
		ca.add(Calendar.DAY_OF_MONTH, -1);
		return df.format(ca.getTime());
	}

	/* 获取最近三个月的第一天 */
	public static String getbeforethreeMonthFirstday() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, -3);
		calendar.set(Calendar.DAY_OF_MONTH, calendar
				.getActualMinimum(Calendar.DAY_OF_MONTH));
		System.out.println(sdf.format(calendar.getTime()));
		return sdf.format(calendar.getTime());
	}

	/* 获取最近三个月的最后一天 */
	public static String getLastDayOfthreeMonth() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar ca = Calendar.getInstance();
		ca.add(Calendar.MONTH, -1);
		ca.set(Calendar.DAY_OF_MONTH, 1);
		df.format(ca.getTime());
		ca.add(Calendar.MONTH, 1);
		ca.add(Calendar.DAY_OF_MONTH, -1);
		return df.format(ca.getTime());
	}

	/**
	 * 取得前一年的日期
	 * 
	 * @return
	 */
	public static String getBeforeYear() {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.YEAR, -1);// 得到前一年
		System.out.println(sdf.format(calendar.getTime()));
		return sdf.format(calendar.getTime());
	}

	public static String[] getFindDay() {
		String[] days = new String[2];
		sdf = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdf.format(new Date());

		String firstday = getCurrentMonday();
		if (today.equals(firstday)) {
			firstday = getPreviousMonday();
		}
		days[0] = firstday;
		days[1] = today;
		return days;
	}

	public static String[] getFindYesterDay() {
		String[] days = new String[2];
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String today = sdf.format(new Date());

		days[0] = getYesterday();
		days[1] = today;
		return days;
	}

	/**
	 * 
	 * @param reqtime
	 * @return
	 */
	public static String getTime(String reqtime) {
		if (null != reqtime) {
			int index = reqtime.indexOf("年");
			if (index > 0) {
				String year = reqtime.substring(0, 2);
				String month = reqtime.substring(3, 5);
				String day = reqtime.substring(6, 8);
				String date = "20" + year + "-" + month + "-" + day;
				return date;
			}
		}
		return null;
	}

	/***************************************************************************
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public static Properties getProp(String path) throws IOException {
		Properties prop = null;
		if (null != path && !"".equals(path)) {
			prop = new Properties();
			InputStream in = new FileInputStream(new File(path));
			if (null != in) {
				prop.load(in);
			}
			in.close();
		}
		return prop;
	}

	/**
	 * 检查字符串不为NULL 和 空字符
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkStr(String value) {
		boolean flag = false;
		if (null != value && !"".equals(value) && value.length() > 0) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 检查文件是否存在
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkFile(String value) {
		boolean flag = false;
		if (checkStr(value)) {

			File f;
			try {
				f = new File(value);
				if (f.exists()) {
					if (f.isFile()) {
						flag = true;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return flag;
	}

	/**
	 * 检查目录是否存在
	 * 
	 * @param value
	 * @return
	 */
	public static boolean checkDir(String value) {
		boolean flag = false;
		if (checkStr(value)) {
			File f = new File(value);
			if (f.exists()) {
				if (f.isDirectory()) {
					flag = true;
				}
			}
		}
		return flag;
	}

	/**
	 * 检查集合是否为空
	 * 
	 * @param coll
	 * @return
	 */
	public static boolean checkColl(Collection<?> coll) {
		boolean flag = false;
		if (null != coll) {
			if (coll.size() > 0) {
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 检查集合是否为空
	 * 
	 * @param objs
	 * @return
	 */
	public static boolean checkArray(Object[] objs) {
		boolean flag = false;
		if (null != objs) {
			if (objs.length > 0) {
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 检查Map 是否为空
	 * 
	 * @param map
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean checkMap(Map map) {
		boolean flag = false;
		if (null != map) {
			if (map.size() > 0) {
				flag = true;
			}
		}
		return flag;
	}

	public static boolean checkInteger(Object obj) {
		boolean flag = false;
		String regx = "^\\d+$";
		flag = checkRegx(obj, regx);
		return flag;
	}

	public static boolean checkFloat(Object obj) {
		boolean flag = false;
		String regx = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
		flag = checkRegx(obj, regx);
		System.out.println(flag);
		return flag;
	}

	public static boolean checkRegx(Object obj, String regx) {
		boolean flag = false;
		if (null != obj) {
			if (null != regx && !"".equals(regx)) {
				flag = Pattern.compile(regx).matcher(obj.toString()).find();
			}
		}
		return flag;
	}

	/**
	 * 
	 * @param name
	 * @param type
	 * @param map
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static boolean checkMapKey(String name, String type, Map map) {
		boolean flag = false;
		if (checkStr(name) && checkStr(type) && checkMap(map)) {
			Set<String> set = map.keySet();
			Iterator it = set.iterator();
			type = type == null ? "" : "." + type;
			String vkey = name + type;
			while (it.hasNext()) {
				String key = (String) it.next();
				if (key.equals(vkey)) {
					flag = true;
					break;
				}
			}
		}
		return flag;
	}

	@SuppressWarnings("rawtypes")
	public boolean checkMapKey(Map map, String key) {
		Object[] objs = map.keySet().toArray();
		if (Tools.checkArray(objs)) {
			for (int i = 0; i < objs.length; i++) {
				if (objs[i].toString().equals(key)) {
					return true;
				}
			}
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	public boolean checkMapKeys(Map map, String[] keys) {
		String some = map.keySet().toArray().toString();
		if (Tools.checkArray(keys)) {
			int len = keys.length;
			int exist = 0;
			for (int i = 0; i < len; i++) {
				if (keys[i].indexOf(some) > 1) {
					exist++;
				}
			}
			if (len == exist) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 格式化XML
	 * 
	 * @param xml
	 * @param src
	 * @param newSrc
	 * @return
	 */
	@SuppressWarnings("unused")
	public static String replace(String xml, String src, String newSrc) {
		String before = xml.substring(0, xml.indexOf(src));
		String end = xml.substring(xml.indexOf(src) + src.length(), xml
				.length());
		String m;
		if (end.startsWith("/")) {
			end = end.substring(end.indexOf("/"), end.length());

		} else if (end.startsWith(" ")) {
			m = end.substring(end.indexOf(" "), end.indexOf(" "));
			src += m;
		} else {

		}

		xml = xml.replace(src, newSrc);
		return xml;

	}

	/**
	 * 生成UUID的方法
	 * 
	 * @return
	 */
	public static String getUUID() {
		String s = UUID.randomUUID().toString();
		// System.out.println(s);
		// 去掉“-”符号
		String str = s.substring(0, 8) + s.substring(9, 13)
				+ s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
		return str;
	}


	
	/***
	 * 
	 * @return
	 */
	public static String getReqIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}


	public static Map<String, Object> doMap(String key, Object value) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(key, value);
		return map;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map<String, Object> getParameters(HttpServletRequest request) {
		Map req = request.getParameterMap();
		if ((req != null) && (!req.isEmpty())) {
			Map p = new HashMap();
			Collection keys = req.keySet();
			for (Iterator i = keys.iterator(); i.hasNext();) {
				Object key = i.next();
				Object value = req.get(key);
				Object v = null;
				if ((value.getClass().isArray())
						&& (((Object[]) value).length == 1)) {
					v = ((Object[]) value)[0];
				} else {
					v = value;
				}
				if ((v != null) && ((v instanceof String))) {
					String s = ((String) v).trim();
					if (s.length() > 0) {
						p.put(key, s);
					}
				}
			}
			return p;
		}
		return null;
	}


	public static boolean checkTypeByPicture(String fileName) {
		String video = Constant.FILE_TYPE_PICTUER;
		boolean flag = false;
		if (checkStr(fileName)) {
			String ext = null;
			if (fileName.indexOf(".") >= 0) {
				ext = fileName.substring(fileName.lastIndexOf(".") + 1,
						fileName.length());
			} else if (fileName.indexOf("/") >= 0) {
				ext = fileName.substring(fileName.lastIndexOf("/") + 1,
						fileName.length());
			} else if (fileName.indexOf("\\") >= 0) {
				ext = fileName.substring(fileName.lastIndexOf("\\") + 1,
						fileName.length());
			} else if (fileName.indexOf("\\\\") >= 0) {
				ext = fileName.substring(fileName.lastIndexOf("\\") + 2,
						fileName.length());
			} else
				ext = fileName;
			if (video.indexOf(ext) > 0) {
				flag = true;
			}
		}
		return flag;
	}
    
	/**将秒转换为 xx:xx:xx格式*/
	public static String secToTime(int time) {
		String timeStr = null;
		int hour = 0;
		int minute = 0;
		int second = 0;
		if (time <= 0)
			return "00:00";
		else {
			minute = time / 60;
			if (minute < 60) {
				second = time % 60;
				timeStr = unitFormat(minute) + ":" + unitFormat(second);
			} else {
				hour = minute / 60;
				if (hour > 99)
					return "99:59:59";
				minute = minute % 60;
				second = time - hour * 3600 - minute * 60;
				timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":"
						+ unitFormat(second);
			}
		}
		return timeStr;
	}


	
	
	
	public static int getRandomNum(){
		 Random random2 = new Random();
		 return random2.nextInt();
	}
	
	

	public static String unitFormat(int i) {
		String retStr = null;
		if (i >= 0 && i < 10)
			retStr = "0" + Integer.toString(i);
		else
			retStr = "" + i;
		return retStr;
	}
    
	/**获取IP*/
	public static String getIp() {
		String ip = "";
		try {
			InetAddress inet = InetAddress.getLocalHost();
			ip = inet.getHostAddress();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ip;
	}

	//根据地址信息获取经纬度
	public static JSONObject addressTOpoint(String cityname,String districtname,String addressname) throws Exception{
		//地址信息
		String address = cityname+districtname+initaddress(addressname);
		//去除空格
		address = address.replace(" ", "");
		//请求地址
		String url = MapInfo.ADDRESS_POINT.replace("MAPKEY", MapInfo.MAPKEY).replace("ADDRESS", address);
		//获取结果
		String result = HttpUtils.sendHttp(url);
		//如果获取失败，则重新获取
		if(result.length()==0){
			for(int i=0;i<10;i++){
				result = HttpUtils.sendHttp(url);
				if(result.length()!=0){
					break;
				}
			}
		}
		//截取信息
		String init = result.substring(result.indexOf("location")+10,result.indexOf("precise")-2);
		//json
		JSONObject obj = JSONObject.parseObject(init);
		return obj;
	}
	//格式化街道信息
		public static String initaddress(String content) throws Exception {
			//记录内容
			String str = content;
			char[] array = content.toCharArray();
			for (int i = 0; i < array.length; i++) {
				//判断是否为数字
				if (Character.isDigit(array[i])) {
					//判断当前数字非结尾
					if(i!=array.length-1){
						if (!Character.isDigit(array[i + 1])) {
							if(!Character.isDigit(array[array.length-1])){
								str = content.substring(0, i + 2);
								break;
							}else{
								str = content.substring(0, i + 1);
								break;
							}
						}
					}
				}
			}
			return str;
		}
		
		
		
		public static void main(String[] args) {
			try {
				String principalSalt = new SecureRandomNumberGenerator().nextBytes().toHex();
				String principalPwd = new Md5Hash("123456", principalSalt, 2).toString();		
				System.out.println(principalSalt);
				System.out.println(principalPwd);
/*				List<String> list=new ArrayList<String>();
				list.add("222");
				list.add("111");
				Optional<String> bbb=list.parallelStream().filter(item ->true).findFirst();
				Optional<String> aaa=Optional.of("bam"); 
				if(aaa.isPresent()){
					System.out.println(aaa.get());
				}
*///				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}
